import copy
import json
import os
import random

from datetime import datetime
from django.shortcuts import render,redirect,HttpResponse
from django.http.request import QueryDict
from django.core.validators import ValidationError
from django.views.decorators.csrf import csrf_exempt
from django.http.response import JsonResponse
from django.forms.utils import ErrorDict
from io import BytesIO
from openpyxl import load_workbook
from django.conf import settings

from web_user import models
from utils.ModelForms import MyForm,PrettyModel,PrettyEditModel,\
    AdminModleForm,AdminEditModleForm,AdminResetModelForm,TaskModelForm,OrerModelForm,CityModelForm
from utils.pagination import Pagination
from utils.Forms import LoginForm,UpForm
from utils.code import check_code
from django.core.files.uploadedfile import InMemoryUploadedFile


# Create your views here.


def depart_list(request):
    """
    部门列表
    """
    # 去数据库中获取所有的部门列表
    # [对象，对象，对象]
    queryset = models.Department.objects.all()
    return render(request,"web_user/depart_list.html",{"queryset":queryset})

def depart_add(request):
    """
    新增部门
    """
    # 判断请求是get请求还是post请求
    # 如果是get请求则返回页面，post请求则提交数据到数据库
    if request.method == "GET":
        return render(request,"web_user/depart_add.html")

    # 获取POST请求提交过来的数据(title输入为空)
    title = request.POST.get("title")
    # 将数据写入数据库
    models.Department.objects.create(titile=title)
    # 重定向回部门列表页面
    return redirect("/depart/list/")

def depart_delete(request):
    """
    删除部门
    """
    # http://127.0.0.1:8000/depart/delete/?nid=1
    # 获取部门id
    nid = request.GET.get('nid')
    # 删除部门
    models.Department.objects.filter(id=nid).delete()
    # 重定向回部门列表页面
    return redirect("/depart/list/")

def depart_edit(request,nid):
    """
    修改部门
    nid的值就是url中真实传过来的值
    # http://127.0.0.1:8000/depart/10/edit/
    # http://127.0.0.1:8000/depart/2/edit/
    # http://127.0.0.1:8000/depart/5/edit/
    """
    if request.method == "GET":
        # 根据nid获取它对应的数据库中的数据 [obj,]
        obj = models.Department.objects.filter(id=nid).first()
        title = obj.titile
        return render(request,"web_user/depart_edit.html",{"title":title})

    # 获取Post请求提交的数据,也就是用户提交的标题
    title = request.POST.get("title")
    # 将修改的数据提交到数据库中
    models.Department.objects.filter(id=nid).update(titile=title)
    # 重定向回部门列表页面
    return redirect("/depart/list/")

def depart_multi(request):
    """
    批量上传(Excel)文件
    """
    # 1.获取用户上传的文件对象
    file_obj = request.FILES.get("exampleInputFile")
    # print(type(file_obj))  # <class 'django.core.files.uploadedfile.InMemoryUploadedFile'>
    # InMemoryUploadedFile()

    # 2.对象传递给openpyxl,由openpyxl打开excel，然后读取数据
    work_obj = load_workbook(filename=file_obj) # 打开excel文件
    sheet = work_obj.worksheets[0] # 获取excel中第零个sheet

    # 3.循环获取每一行数据
    for row in sheet.iter_rows(min_row=2):
        text = row[0].value
        # print(text)
        # print(row[0])
        # 将提交的数据上传到数据库中(对数据进行校验吗，数据不存在则添加到数据库中)
        exists = models.Department.objects.filter(titile=text).exists()
        if not exists:
            models.Department.objects.create(titile=text)

    return redirect("/depart/list/")


def user_list(request):
    """
    用户列表
    """
    # 获取用户表中的所有数据 [对象,对象,对象]
    queryset = models.UserInfo.objects.all()

    # 用python代码的方式进行读取数据
    # for obj in queryset:
    #     print(obj.id,obj.name,obj.password,obj.gender,obj.salary,obj.create_time,obj.depart_id)
    #     # gender(性别)在django中的models定义的是可选择的形式 1表示男性 2表示女性
    #     # 我们如果想在python代码中显示正确的对应的中文性别显示可以利用obj.get_字段名称_display()方法来实现
    #     print(obj.get_gender_display())
    #     # 对于数据库中存储的datetime类型的数据 2020-03-03 00:00:00+00:00
    #     # 我们如果想在python中将datetime类型的数据转换成字符串，需要用到strftime("%Y-%m-%d-%H-%M")方法
    #     print(obj.create_time,type(obj.create_time))
    #     print(obj.create_time.strftime("%Y-%m-%d"))
    #     # 对于数据库中其中一个表的字段和另外的表中的字段存在关联(表1的depart与表2的id关联)
    #     # 如果我们想在python中获取到字段关联后的值，我们需要采用obj.depart(表1),django内部会自动帮我们做关联
    #     print(obj.depart.titile)

    return render(request,'web_user/user_list.html',{"queryset":queryset})

def user_add(request):
    """
    新增用户(最原始方法)
    """
    if request.method == "GET":
        # print(models.UserInfo.gender_tup) #((1, '男'), (2, '女'))
        context = {
            "gender_tup":models.UserInfo.gender_tup, # models中定义的性别类型(元祖)
            "depeart_list":models.Department.objects.all() # 数据库中已经存在的部门
        }
        return render(request=request,template_name="web_user/user_add.html",context=context)

    # 获取用户提交的数据
    user = request.POST.get("user")
    pwd = request.POST.get("pwd")
    age = request.POST.get("age")
    salary = request.POST.get("salary")
    create_time = request.POST.get("ct")
    gender = request.POST.get("gd")
    depart_id = request.POST.get("dp")

    # 添加到数据库中
    models.UserInfo.objects.create(name=user,password=pwd,age=age,
                                   salary=salary,create_time=create_time,
                                   gender=gender,depart_id=depart_id)

    # 返回用户列表页面
    return redirect("/user/list/")

def user_model_form_add(request):
    """
    新增用户(ModelForm)
    """
    if request.method == "GET":
        form = MyForm()
        context = {
            "form":form
        }
        return render(request=request,template_name="web_user/user_model_form_add.html",context=context)

    # 用户POST提交的数据，必须进行数据校验
    form = MyForm(data=request.POST) # 利用data参数将用户提交的数据交给ModelForm，会取对应的字段
    # 利用is_valid()方法校验数据是否合法
    if form.is_valid():
        # 如果数据合法，就利用save()保留到数据库
        # print(form.cleaned_data) # cleaned_data获取所有的数据
        # {'name': '玲', 'age': 27,
        #  'gender': 2, 'password': '123456',
        # 'depart': < Department: 销售部 >,
        # 'salary': Decimal('10000'),
        # 'create_time': datetime.datetime(2020, 10, 30, 0, 0, tzinfo= < UTC >)
        # }
        form.save()
        # 保存后返回用户列表页面
        return redirect('/user/list')

    # 校验失败返回错误信息在页面上
    else:
        context = {
            "form":form
        }
        return render(request=request,template_name="web_user/user_model_form_add.html",context=context)

def user_edit(request,nid):
    """
    编辑用户
    """
    # 根据id获取数据库当前行的数据
    obj = models.UserInfo.objects.filter(id=nid).first()
    # 使用instance参数就可以将数据库获取的值，在字段中显示出默认值来
    if request.method == "GET":
        form = MyForm(instance=obj)
        context = {
            "form":form
        }
        return render(request=request,template_name="web_user/user_edit.html",context=context)

    # 对用户提交的数据进行校验,校验成功将用户修改的信息提交到数据库中
    # 一定要使用instance参数将代表的这一行数据，
    # 否则就不知道是将哪一行数据库更新到数据库，直接在数据库中进行创建了
    form = MyForm(data=request.POST,instance=obj)
    if form.is_valid():
        # 默认保存的是用户输入的所有数据,如果想要再用户输入以外增加一点值
        # form.instance.字段名 = 值
        form.save()
        return redirect('/user/list/')
    else:
        context = {
            "form": form
        }
        return render(request=request,template_name="web_user/user_edit.html",context=context)

def user_delete(request):
    """
    删除用户
    """
    # 根据nid查出对应的用户id
    nid = request.GET.get("nid")
    models.UserInfo.objects.filter(id=nid).delete()
    return redirect('/user/list/')




def pretty_list(request):
    """
    靓号列表
    """

    # 搜索功能
    # 如果搜索框中有输入值，就展示符合搜索框条件的数据
    # 搜索框中没有值，则展示数据中全部内容
    data_dict = {}
    search_data = request.GET.get("q",default="")
    # 如果值存在，则在查询的data_dict新增一个mobile__contains=value的查询条件
    if search_data:
        data_dict["mobile__contains"]=search_data
    # 按照级别从高到底排序,使用order by level desc;
    # 相当于select * from web_user_prettynum order by level desc;
    queryset = models.PrettyNum.objects.filter(**data_dict).order_by("-level")

    page_obj = Pagination(request,queryset)
    page_queryset = page_obj.page_queryset   # 分完页的数据
    page_string = page_obj.html()  # 分页的页码

    context = {
        "search_data": search_data,
        "queryset":page_queryset,
        "page_string":page_string
    }
    return render(request,"web_user/pretty_list.html",context=context)

def pretty_add(request):
    """
    新增靓号
    """
    if request.method == "GET":
        form = PrettyModel()
        return render(request,"web_user/pretty_add.html",{"form":form})

    # 获取用户提交的数据
    form = PrettyModel(data=request.POST)
    if form.is_valid():
        # 保存到数据库
        form.save()
        return redirect("/pretty/list")
    return render(request,"web_user/pretty_add.html",{"form":form})

def pretty_edit(request,nid):
    """
    编辑靓号
    """
    # 根据传过来的id得到数据库中对应的信息 [对象,]
    obj = models.PrettyNum.objects.filter(id=nid).first()
    # print(obj, type(obj))
    if request.method == "GET":
        form = PrettyEditModel(instance=obj)
        return render(request,"web_user/pretty_edit.html",{"form":form})

    # 获取用户提交的数据，并且将对应的数据在数据库中进行修改
    data = request.POST
    form = PrettyEditModel(data=data,instance=obj)
    if form.is_valid():
        form.save()
        return redirect("/pretty/list/")
    return render(request,"web_user/pretty_edit.html",{"form":form})

def pretty_delete(request):
    """
    删除靓号
    """
    # 根据id查询数据，然后进行删除
    nid = request.GET.get("nid")
    models.PrettyNum.objects.filter(id=nid).delete()
    return redirect("/pretty/list/")



def admin_list(request):
    """
    管理员列表
    """
    # 搜搜
    dict_data = {}
    search_data = request.GET.get("q",default="")
    if search_data:
        dict_data["username__contains"]=search_data
    queryset = models.Admin.objects.filter(**dict_data).order_by("-id")

    #分页
    page_obj =Pagination(request=request,queryset=queryset)
    page_queryset = page_obj.page_queryset
    page_string = page_obj.html()
    context={
        "search_data":search_data,
        "queryset":page_queryset,
        "page_string":page_string
    }
    return render(request,"web_user/admin_list.html",context)


def admin_add(request):
    """
    添加管理员账户
    """
    # GET请求
    if request.method == "GET":
        form = AdminModleForm()
        return render(request,"web_user/admin_add.html",{"form":form})
    # POST请求
    form = AdminModleForm(data=request.POST)
    if form.is_valid():
        # form.cleaned_data获取合法的所有的提交的数据
        # print(form.cleaned_data)
        #{'username': 'laowang', 'password': '123', 'confirm_pwd': '111'}
        form.save()
        return redirect("/admin/list/")
    return render(request,"web_user/admin_add.html",{"form":form})


def admin_edit(request,nid):
    """
    编辑管理员账户
    """
    # 如果有值则返回一个对象,否则返回一个None
    row_obj = models.Admin.objects.filter(id=nid).first()
    title = "编辑管理员"
    if request.method == "GET":
        form = AdminEditModleForm(instance=row_obj)
        if not row_obj:
            msg = "用户不存在"
            return render(request,"web_user/error.html",{"msg":msg})
        return render(request,"web_user/change.html",{"form":form,"title":title})
    form = AdminEditModleForm(data=request.POST,instance=row_obj)
    if form.is_valid():
        form.save()
        return redirect("/admin/list/")
    return render(request,"web_user/change.html",{"form":form,"title":title})


def admin_delete(request,nid):
    """
    删除管理员账户
    """
    row_obj = models.Admin.objects.filter(id=nid).first()
    if not row_obj:
        msg = "用户不存在"
        return render(request, "web_user/error.html", {"msg": msg})
    row_obj.delete()
    return redirect("/admin/list/")

def admin_reset(request,nid):
    """
    重置密码
    """
    row_obj = models.Admin.objects.filter(id=nid).first()
    title = f"重置{row_obj.username}的密码"
    if not row_obj:
        msg = "用户不存在"
        return render(request, "web_user/error.html", {"msg": msg})

    if request.method == "GET":
        form = AdminResetModelForm()
        return render(request, "web_user/change.html", {"form": form, "title": title})
    # POST请求
    form = AdminResetModelForm(data=request.POST,instance=row_obj)
    if form.is_valid():
        form.save()
        return redirect("/admin/list/")
    return render(request,"web_user/change.html",{"form":form,"title":title})



def login(request):
    """
    登录
    """
    # GET请求
    if request.method=="GET":
        form = LoginForm()
        return render(request,"web_user/login.html",{"form":form})
    # POST请求
    form = LoginForm(data=request.POST)
    if form.is_valid():
        # 验证成功之后，获取到的用户名和密码以及验证码
        # {'username': 'test', 'password': '1231'}
        # {'username': 'test', 'password': '67fb6c25b5c783b0e80463190d0415ae',"code":XXX}
        # print(form.cleaned_data)

        # 验证码的校验
        # 首先获取图片验证码
        # 利用pop()取出用户输入的图片验证码，并且在字典中删除掉，以便后面进行数据库的校验
        user_input_code = form.cleaned_data.pop("image_code")
        code = request.session.get("image_code","") # 生成的验证码
        # 输入的验证码和生成的验证码进行比较
        if user_input_code.upper() != code.upper():
            form.add_error(field="image_code",error="验证码错误")
            return render(request, "web_user/login.html", {"form": form})

        # 去数据库中校验用户名和密码是否正确，获取用户对象，为空返回None
        data_dict = form.cleaned_data
        row_obj = models.Admin.objects.filter(**data_dict).first()
        # 用户名和密码不正确
        if not row_obj:
            form.add_error(field="password",error="用户名或密码错误") # add_error()可以主动添加字段错误信息
            return render(request,"web_user/login.html",{"form":form})

        # 用户名和密码正确
        # 网站生成随机字符串；写到用户浏览器的cookie和session中;
        # django只需要request.session["key"]=value就可以实现这个功能
        request.session["info"] = {"id":row_obj.id,"name":row_obj.username} # 将当前用户的用户名和id写入到session中
        request.session.set_expiry(60*60*24*7) # 将登录的session有效信息超时时间设置为7天
        return redirect("/admin/list/")
    return render(request,"web_user/login.html",{"form":form})


def logout(request):
    """
    注销
    """
    # request.session.clear()清除当前用户的session
    request.session.clear()
    return redirect("/login/")


def image_code(request):
    """
    生成图片验证码
    """
    # 调用pillow函数生成验证码的图片
    img,code_str = check_code()

    # 将生成的图片验证码放到session中(以便于后面登录进行校验)
    request.session["image_code"] = code_str
    # 为其设置一个超时时间，防止重复利用
    request.session.set_expiry(60)

    # print(code_str) # LEACP
    # 将返回图片对象给浏览器。为了方便返回给浏览器
    # 使用特殊的BytesIO()将图片的信息写入到内存中
    stream = BytesIO()
    img.save(stream,"png")
    # 使用getvalue()获取BytesIO对象中的全部内容
    return HttpResponse(stream.getvalue())



def task_list(request):
    """
    任务管理
    """
    queryset = models.Task.objects.all().order_by("-id")
    page_obj = Pagination(request,queryset)
    form = TaskModelForm()
    context = {
        "queryset": page_obj.page_queryset,
        "form":form,
        "page_string":page_obj.html()
    }
    return render(request,"web_user/task_list.html",context)


# 使用csrf_exempt让请求免除csrf_token认证
@csrf_exempt
def task_add(request):
    """
    添加任务
    """
    # print(request.POST) #<QueryDict: {'title': ['qweqew'], 'detail': ['1231231'], 'level': ['1'], 'user': ['9']}>

    # 1.用户发送过来的数据进行校验(ModelForm进行校验)
    form = TaskModelForm(data=request.POST)
    if form.is_valid():
        form.save()
        data_dict = {"status": True}
        return HttpResponse(json.dumps(data_dict))

    # print(type(form.errors))   # <class 'django.forms.utils.ErrorDict'>
    # print(form.errors.as_json()) # form.errors.as_json()将错误信息转化为json格式的数据
    # {"title": [{"message": "\u8fd9\u4e2a\u5b57\u6bb5\u662f\u5fc5\u586b\u9879\u3002", "code": "required"}], "detail": [{"message": "\u8fd9\u4e2a\u5b57\u6bb5\u662f\u5fc5\u586b\u9879\u3002", "code": "required"}], "user": [{"message": "\u8fd9\u4e2a\u5b57\u6bb5\u662f\u5fc5\u586b\u9879\u3002", "code": "required"}]}

    data_dict = {"status": False,"error":form.errors}
    return HttpResponse(json.dumps(data_dict,ensure_ascii=False))


# 使用csrf_exempt让请求免除csrf_token认证
@csrf_exempt
def task_ajax(request):
    """
    学习ajax
    """
    # 获取ajax请求提交的数据
    print(request.GET)
    print(request.POST) # <QueryDict: {'n1': ['123'], 'n2': ['456']}>

    # 返回json格式的数据
    data_dict = {"status":True,"data":[11,22,33,44]}
    json_str = json.dumps(data_dict)
    return HttpResponse(json_str)
    # return JsonResponse(data_dict)


def order_list(request):
    """
    订单列表
    """
    queryset = models.Order.objects.all().order_by('-id')
    page_obj = Pagination(request,queryset)
    form = OrerModelForm()
    context = {
        "queryset": page_obj.page_queryset,
        "form":form,
        "page_string":page_obj.html(),
    }
    return render(request,"web_user/oder_list.html",context)


@csrf_exempt
def order_add(request):
    """
    新建订单(ajax请求)
    """
    form = OrerModelForm(data=request.POST)
    if form.is_valid():
        # print(form.cleaned_data)  # {'title': 'iphone', 'price': 8999, 'status': 1, 'admin': <Admin: test>}
        # oid为订单号，用户没有在前端页面输入，数据库中这个字段必填
        # 不输入这个字段值会报错 使用form.instance.oid来额外增加一些不是用户输入的值(自己计算出来) 设置订单号
        # 然后再保存到数据库中
        form.instance.oid = datetime.now().strftime("%Y%m%d%H%M%S") + str(random.randint(1000,9999))

        # 管理员 数据库中存储的字段叫admin_id
        # 获取当前登录用户的id(之前登录时session中保存了用户id)
        # 将当前的admin_id的值设为当前用户登录的id，保存到数据库中
        form.instance.admin_id = request.session["info"]["id"]

        # 保存到数据库中
        form.save()
        return JsonResponse({"status":True})

    data_dict = {"status":False,"error":form.errors}
    return HttpResponse(json.dumps(data_dict))


def order_delete(request):
    """
    删除订单(ajax)
    """
    # 获取get请求的参数uid,如果没有设置为空
    uid= request.GET.get("uid","")

    # 判断数据库有没有这个id
    row_obj = models.Order.objects.filter(id=uid).first()
    if row_obj:
        row_obj.delete()
        return HttpResponse(json.dumps({"status":True}))
    return JsonResponse({"status":False,"error":"删除失败，数据不存在"})


def order_detail(request):
    """
    获取每行订单的详细信息(ajax)
    """

    '''
    # 方式一：
    uid = request.GET.get("uid")
    row_obj = models.Order.objects.filter(id=uid).first()
    if not row_obj:
        return JsonResponse({"status":False,"error":"数据不存在"})

    result = {
        "status": True,
        "data":{
            "title": row_obj.title,
            "price": row_obj.price,
            "status": row_obj.status
        }
    }
    return HttpResponse(json.dumps(result))
    '''

    # 方式二:
    uid = request.GET.get("uid")

    # values()返回字典,字典的组成取决于你values中写的是什么{'title': 'imac', 'price': 14999, 'status': 1}
    # 转换为字典形式之后就可以直接进行序列化，不需要想方式一中去一个个取值
    row_obj = models.Order.objects.filter(id=uid).values("title","price","status").first()
    # print(row_obj) # {'title': 'imac', 'price': 14999, 'status': 1}
    if not row_obj:
        return JsonResponse({"status": False, "error": "数据不存在！！"})

    result = {
        "status": True,
        "data": row_obj
    }
    return HttpResponse(json.dumps(result))

@csrf_exempt
def order_edit(request):
    """
    编辑订单(ajax)
    """
    # 获取url中传入过来的uid
    uid = request.GET.get("uid")

    # 查询数据是否存在
    row_obj = models.Order.objects.filter(id=uid).first()
    if not row_obj:
        return JsonResponse({"status": False, "tips": "数据不存在！！！"})

    # uid存在，则进行数据格式的校验
    form = OrerModelForm(data=request.POST,instance=row_obj)
    if form.is_valid():
        form.save()
        return HttpResponse(json.dumps({"status": True}))
    return JsonResponse({"status": False, "error": form.errors})


def chart_list(request):
    """
    数据统计列表
    """
    return render(request,"web_user/chart_list.html")


def chart_bar(request):
    """
    构造柱状图的数据
    """
    # 数据正常从数据库中获取
    legend = ['老张', '老王']
    series_list = [
        {
            "name": '老张',
            "type": 'bar',
            "data": [40, 20,100 ,50, 60, 80]
        },
        {
            "name": '老王',
            "type": 'bar',
            "data": [45, 30, 20, 110, 40, 70]
        },
    ]
    xAxis_list = ['1月', '2月', '3月', '4月', '5月', '6月']

    result = {
        "status":True,
        "data":{
            "legend": legend,
            "series": series_list,
            "xAxis": xAxis_list,
        }
    }
    return JsonResponse(result)


def chart_pie(request):
    """
    构造饼图的数据
    """
    series_data = [
        {"value": 1048, "name": 'IT研发部'},
        {"value": 735, "name": '销售部'},
        {"value": 580,"name": '新媒体部'},
        {"value": 484, "name": '投资部'},
        {"value": 300, "name": '人力资源部'}
    ]

    result = {
        "status":True,
        "data":{
            "series_data":series_data
        }
    }
    return JsonResponse(result)

def chart_line(request):
    """
    构造折线图数据
    """
    legend = ['上海', '深圳','广州','南京','武汉']
    series_list = [
        {
            "name": '南京',
            "type": 'line',
            "stack": 'Total',
            "data": [120, 132, 101, 134, 90, 230, 210]
        },
        {
            "name": '广州',
            "type": 'line',
            "stack": 'Total',
            "data": [220, 182, 191, 234, 290, 330, 310]
        },
        {
            "name": '武汉',
            "type": 'line',
            "stack": 'Total',
            "data": [150, 232, 201, 154, 190, 330, 410]
        },
        {
            "name": '上海',
            "type": 'line',
            "stack": 'Total',
            "data": [320, 332, 301, 334, 390, 330, 320]
        },
        {
            "name": '深圳',
            "type": 'line',
            "stack": 'Total',
            "data": [820, 932, 901, 934, 1290, 1330, 1320]
        }
    ]
    xAxis_list = ['1月', '2月', '3月', '4月', '5月', '6月']


    result = {
        "status":True,
        "data":{
            "legend": legend,
            "series": series_list,
            "xAxis": xAxis_list,
        }
    }
    return JsonResponse(result)


def highcharts_list(request):
    """
    构造highchart示例
    """
    return render(request,"web_user/highcharts_list.html")


def upload_list(request):
    """
    上传文件
    """
    if request.method == "GET":
        return render(request,"web_user/upload_list.html")

    # <QueryDict: {'csrfmiddlewaretoken': ['sHlkURynpi4Fo2bDMhTzQ7QnBBbiZmsTA8PJcUiVmYnd0SnyHcYmSd8tfqS6M4KO'], 'username': ['qwe']}>
    # print(request.POST)  # 请求体中发过来的数据
    # <MultiValueDict: {'avatar': [<InMemoryUploadedFile: Snipaste_2022-06-26_14-42-40.png (image/png)>]}>
    # print(request.FILES) # 请求发过来的文件

    # 获取文件对象
    file_object = request.FILES.get("avatar")
    print(file_object.name) # 获取文件名: Snipaste_2022-06-26_14-42-40.png

    # 读取文件，写入到文件中
    f = open(file_object.name,mode="wb")
    for chunk in file_object.chunks():
        f.write(chunk)
    f.close()

    return HttpResponse("提交成功")


def upload_from(request):
    """
    文件上传Form
    """
    title = "文件上传"
    if request.method == "GET":
        form = UpForm()
        return render(request,"web_user/upload_from.html",{"form":form,"title":title})

    # 获取用户提交的数据(包括文件和表单数据)
    form = UpForm(data=request.POST,files=request.FILES)
    if form.is_valid():
        # print(form.cleaned_data) #{'name': 'test', 'age': 36, 'img': <InMemoryUploadedFile: Snipaste_2022-06-26_14-42-40.png (image/png)>}
        # 读取到内容后，处理每个字段的数据
        # 1.读取图片内容，写入到文件夹中并获取文件的路径
        img_obj = form.cleaned_data.get("img")

        # media_path1 = os.path.join(settings.MEDIA_ROOT,img_obj.name)
        # print(media_path1) # D:\Django_env_study\django_project\Employee_manage\media\Snipaste_2022-06-26_14-42-40.png
        media_path = os.path.join("media",img_obj.name)
        # print(media_path) # media\Snipaste_2022-06-26_14-42-40.png

        with open(file=media_path,mode="wb")as f:
            for chunk in img_obj.chunks():
                f.write(chunk)

        # 2.将图片文件路径写入到数据库
        models.Boss.objects.create(
            name=form.cleaned_data["name"],
            age=form.cleaned_data["age"],
            img=media_path,
        )

        return HttpResponse("提交成功")
    return render(request, "web_user/upload_from.html", {"form": form, "title": title})



def upload_model_form(request):
    """
    文件上传之ModelForm
    """
    title = "ModelForm上传"
    if request.method == "GET":
        form = CityModelForm()
        return render(request,"web_user/upload_from.html",{"title":title,"form":form})

    form = CityModelForm(data=request.POST,files=request.FILES)
    if form.is_valid():
        # 对于文件：自动保存
        # 字段+上传路径写入到数据库
        form.save()
        return HttpResponse("提交成功")
    return render(request, "web_user/upload_from.html", {"title": title, "form": form})


def city_list(request):
    """
    城市列表
    """
    queryest = models.City.objects.all()
    # print(queryest.first().img)
    return render(request,"web_user/city_list.html",{"queryset":queryest})


def city_add(request):
    """
    新建城市
    """
    title = "新建城市"
    if request.method == "GET":
        form = CityModelForm()
        return render(request, "web_user/upload_from.html", {"title": title, "form": form})

    form = CityModelForm(data=request.POST, files=request.FILES)
    if form.is_valid():
        # 对于文件：自动保存
        # 字段+上传路径写入到数据库
        form.save()
        return redirect("/city/list/")
    return render(request, "web_user/upload_from.html", {"title": title, "form": form})
















